import type { VxeTableGridOptions } from '@vben/plugins/vxe-table';

import type { VbenFormSchema } from '#/adapter/form';
import type { OnActionClickFn } from '#/adapter/vxe-table';
import type { SysDict } from '#/api/system/sysdict';

import { useAccess } from '@vben/access';

import { z } from '#/adapter/form';
import { $t } from '#/locales';

const { hasAccessByCodes } = useAccess();

/**
 * 查询参数
 */
export function querySchema(): VbenFormSchema[] {
  return [
    {
      component: 'Input',
      fieldName: 'dictName',
      label: $t('dict.name'),
    },
    {
      component: 'Input',
      fieldName: 'dictKey',
      label: $t('dict.key'),
    },
  ];
}

/**
 * 获取编辑表单的字段配置。如果没有使用多语言，可以直接export一个数组常量
 */
export function formSchema(): VbenFormSchema[] {
  return [
    {
      component: 'Input',
      fieldName: 'dictName',
      label: $t('dict.name'),
      rules: z
        .string()
        .min(2, $t('ui.formRules.minLength', [$t('dict.name'), 2]))
        .max(20, $t('ui.formRules.maxLength', [$t('dict.name'), 20])),
    },
    {
      component: 'Input',
      fieldName: 'dictKey',
      label: $t('dict.key'),
      rules: z
        .string()
        .min(4, $t('ui.formRules.minLength', [$t('dict.key'), 4]))
        .max(30, $t('ui.formRules.maxLength', [$t('dict.key'), 30])),
    },
    {
      component: 'ObjectArray',
      componentProps: {
        objDef: {
          value: '字典值',
          label: '字典标签',
          tableCls: '表格回显样式',
        },
      },
      fieldName: 'dictValue',
      label: $t('dict.value'),
    },
    {
      component: 'Input',
      fieldName: 'remark',
      label: $t('common.remark'),
    },
  ];
}

/**
 * 获取表格列配置
 * @description 使用函数的形式返回列数据而不是直接export一个Array常量，是为了响应语言切换时重新翻译表头
 * @param onActionClick 表格操作按钮点击事件
 */
export function columnsSchema(
  onActionClick?: OnActionClickFn<SysDict>,
): VxeTableGridOptions<SysDict>['columns'] {
  return [
    { title: '序号', type: 'seq', width: 50 },
    {
      field: 'dictName',
      title: $t('dict.name'),
    },
    {
      field: 'dictKey',
      title: $t('dict.key'),
    },
    {
      field: 'remark',
      title: $t('common.remark'),
    },
    {
      field: 'createAt',
      title: $t('common.createTime'),
    },
    {
      cellRender: {
        attrs: {
          nameField: 'dictName',
          onClick: onActionClick,
        },
        name: 'CellOperation',
        options: [
          {
            code: 'edit',
            show: () => {
              return hasAccessByCodes(['sys_dict:edit']);
            },
          },
          {
            code: 'delete',
            text: true,
            show: () => {
              return hasAccessByCodes(['sys_dict:remove']);
            },
          },
        ],
      },
      field: 'operation',
      fixed: 'right',
      align: 'center',
      headerAlign: 'center',
      showOverflow: false,
      title: $t('page.action.action'),
    },
  ];
}
